package com.rover.system.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import com.rover.system.entity.Permission;
import com.rover.system.entity.Resource;
import com.rover.system.entity.Role;
import com.rover.system.entity.User;
import com.rover.system.service.PermissionService;
import com.rover.system.service.ResourceService;
import com.rover.system.service.RoleResourceService;
import com.rover.system.service.UserService;

/**
 * 菜单资源
 */
@Controller
@RequestMapping("/resourceController")
public class ResourceController {

	@Autowired
	private ResourceService resourceService;

	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleResourceService roleResourceService;

	
	@Autowired
	private 	PermissionService permissionService;
	
	
	  @RequestMapping("/getMenu")
	    public void getMenu(HttpServletRequest request, HttpServletResponse response)
	            throws IOException {
	        //资源列表
	        List<Resource> list = resourceService.selectResource(0);
	        //获取当前用户
	        Subject subject = SecurityUtils.getSubject();
	        String userLoginId = (String)subject.getPrincipal();
	        User user = userService.getUserByUserName(userLoginId);
	     List<Role> l=new ArrayList(  user.getRoleList());
	     //获取当前用户权限
	     List<String> permissions = new ArrayList<String>();
	     for(Role r:l){
	    	 List<Permission> permissionList =new ArrayList( r.getPermissions());
	    	 for (Permission permission : permissionList){
	                permissions.add(permission.getPermission());
	            }
	    	 
	     }
	     
	    
	       
	        String str = getMenuTree(list, permissions);
	        response.setContentType("application/json;charset=UTF-8");
	        PrintWriter out = response.getWriter();
	        out.write(str);
	    }

	    private String getMenuTree(List<Resource> list,List<String> permissions) {
	        StringBuilder db = new StringBuilder();
	        db.append("[");
	        for (int i = 0; i < list.size(); i++) {
	            Boolean flag = Boolean.FALSE;
	            Resource menu = list.get(i);
	            String strTemp = "";
	            List<Resource> liChildren = resourceService.getResource(menu.getId(),permissions);
	            if (liChildren.size() > 0){
	                strTemp = " ,\"leaf\": \"false\" ,\"children\": " + getMenuTree(liChildren, permissions);
	                flag = Boolean.TRUE;
	            }else if (menu.getLeaf().equals(1)){
	                strTemp = " ,\"leaf\": \"true\" ";
	                flag = Boolean.TRUE;
	            }
	            if (flag){
	                if ((list.size() - 1) == i) {
	                    db.append("{ \"type\":"+menu.getType()+",\"text\": \"" + menu.getText() + "\",\"url\":\""
	                            + menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
	                            + menu.getId() + "\"" + strTemp + "}");
	                } else {
	                    db.append("{ \"type\":"+menu.getType()+", \"text\": \"" + menu.getText() + "\",\"url\":\""
	                            + menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
	                            + menu.getId() + "\"" + strTemp + "},");
	                }
	            }
	        }
	        db.append(" ]");
	        return db.toString();
	    }

		/*
		 * 返回资源json  
		 * 这个方法根据left属性判断是否有子节点，效率比较高
		 * （注意：这个方法对left属性有着很高的要求，如果left属性有错误，返回的json树会有问题）
		 * 
		 * @li 数据源
		 */
		private String getMenuLeaf(List<Resource> list,List<String> listPermission) {
			StringBuilder db = new StringBuilder();
			db.append("[");
			for (int i = 0; i < list.size(); i++) {
				Resource menu = (Resource) list.get(i);
				String strTemp = "";
				//判断是否字节点（）
				if (menu.getLeaf().equals(1)) {
					strTemp = " ,\"leaf\": \"true\" ";
					
				} else {
					  List<Resource> liChildren = resourceService.getResource(menu.getId(),listPermission);
					strTemp = " ,\"leaf\": \"false\" ,\"children\": "
						+ getMenuLeaf(liChildren, listPermission);
				}
				if ((list.size() - 1) == i) {
					db.append("{ \"type\":"+menu.getType()+",\"text\": \"" + menu.getText() + "\",\"url\":\""
							+ menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
							+ menu.getId() + "\"" + strTemp + "}");
				} else {
					db.append("{ \"type\":"+menu.getType()+", \"text\": \"" + menu.getText() + "\",\"url\":\""
							+ menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
							+ menu.getId() + "\"" + strTemp + "},");
				}
			}
			db.append(" ]");
			return db.toString();
		}
		/*
		 * 获取指定角色的资源
		 * */
		@RequestMapping("/getRoleResource")
		public void getRoleResource(HttpServletRequest request,
				HttpServletResponse response) throws IOException {
			// 此人员对应的角色
			String str = "[]";
			if (request.getParameter("roleId") != null
					&& !request.getParameter("roleId").equals("")) {
		  	List<Permission> listPermission=	permissionService.getListByRoleId(Integer.valueOf( request.getParameter("roleId")));
		  	 List<String> permissions = new ArrayList<String>();
		        if (null != listPermission && listPermission.size() > 0){
		            for (Permission permission : listPermission){
		                permissions.add(permission.getPermission());
		            }
		        }
		        List<Resource> list = resourceService.getResource(0,permissions);
				str = getMenuLeaf(list ,permissions);
			}
			response.setContentType("application/json;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.write(str);
		}
		/*
		 * 角色资源树的时候使用
		 */
		@RequestMapping("/getAllResource")
		public void getAllResource(HttpServletRequest request,
				HttpServletResponse response) throws IOException {
			List<Resource> li = resourceService.selectResource(0);
			String str = checkedTree(li);
			response.setContentType("application/json;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.write(str);
		}

		/*
		 * 返回带有checkbox的树json
		 * 
		 * @li 数据源
		 */
		private String checkedTree(List<?> li) {
			StringBuilder db = new StringBuilder();
			db.append("[");
			for (int i = 0; i < li.size(); i++) {
				Resource menu = (Resource) li.get(i);
				List<Resource> liChildren = resourceService.selectResource(menu
						.getId());
				String strTemp = "";
				if (liChildren.size() > 0) {
					strTemp = " ,\"leaf\": \"false\" ,\"checked\":false,\"children\": "
							+ checkedTree(liChildren);
				} else {
					strTemp = " ,\"leaf\": \"true\",\"checked\":false ";
				}
				if ((li.size() - 1) == i) {
					db.append("{ \"text\": \"" + menu.getText() + "\",\"url\":\""
							+ menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
							+ menu.getId() + "\"" + strTemp + "}");

				} else {
					db.append("{ \"text\": \"" + menu.getText() + "\",\"url\":\""
							+ menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
							+ menu.getId() + "\"" + strTemp + "},");
				}
			}
			db.append(" ]");
			return db.toString();
		}

}
